/*
 * 调用的是本地的map服务器，如果是其他的服务器，需修改
 */
var defaultShopIcon = "/wcsi/img/defaultShop.png";
var defaultEventTypeIcon = "/wcsi/img/defaultEventType.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var tempgraphic;
var g_labels = "";
var g_textsearch = "", g_textvalue = "";
var g_value = "", g_left, g_right;
var arcTool, manhole_cover_p;
var hander;
var centerX = 106.53884704455731;// 120.206354450751;
var centerY = 29.7219072675705;// 30.0725834699399;
var toolbar;
var drawHandler;
var gsvc;// 测量面积
var partLayer;
var gridLayer;
var shopLayer;
var userLayer;
var text_graphic;
var dynamic;
var highLayer;
var gridCenterX = 106.53884704455731;
var gridCenterY = 29.7219072675705;
var interval;
var intervalflashTime;
var intervalflashTimeEvent;
var intervalflashTimeWarning;
var intervalflashTimePart;
var FlickerPointType = "reportFlickerPointType";
var showFlickerPointTyp = FlickerPointType;
var showFlickerEventPointType = "eventFlickerPointType";
var showFlickerWaringPointType = "warningFlickerPointType";
var socketList;
require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct", "esri/tasks/GeometryService" ], function(Map,
		Color, Graphic, InfoTemplate, SpatialReference, HeatmapRenderer,
		OverviewMap, Scalebar, Measurement, Units, TDTLayer, TDTAnnoLayer,
		TDT_ImgLayer, TDT_ImgAnnoLayer, GraphicsLayer,
		ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, FeatureLayer,
		Point, Polyline, Polygon, Circle, TextSymbol, SimpleMarkerSymbol,
		PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Font,
		LabelClass, Query, QueryTask, Draw, Popup, PopupTemplate, dom,
		domConstruct, GeometryService) {
	$("#map").css({"height":+$("#right").height()+"px"}); 
	map = new Map("map", {
		nav: true,
		slider: true,
        sliderPosition: 'bottom-right',
        sliderStyle: 'large',
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 17,
		minZoom : 15,
		maxZoom : 18
	});
	var vec = new TDTLayer();
	var veca = new TDTAnnoLayer();
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);
	// 初始化比例尺
	var scalebar = new Scalebar({
		map : map,
		attachTo : "bottom-left",
		scalebarUnit : "dual",
	});
	scalebar.show();
	drawHandler = Draw;
    dynamic = new ArcGISTiledMapServiceLayer(arcGisUrl
			+ "/arcgis/rest/services/YuelaiMap/MapServer");
	dynamic.id = "dynamic";
	map.addLayer(dynamic);
    dynamic.hide();

	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	highLayer = new FeatureLayer(url + "/15", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		maxScale : 0,
		minScale : 4508.935440959931,
		visible : true,
		id : "highLayer"
	});
	map.addLayer(highLayer);

	highLayer.setMaxScale(0);
	highLayer.setMinScale(4508.935440959931);
	
	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	partLayer = new FeatureLayer(url + "/16", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		maxScale : 0,
		minScale : 4508.935440959931,
		visible : true,
		id : "partLayer"
	});
	map.addLayer(partLayer);

	partLayer.setMaxScale(0);
	partLayer.setMinScale(4508.935440959931);
	
	partLayer.on("mouse-over", function(evt) {
		map.setMapCursor('pointer');
	});
	partLayer.on("mouse-out", function(evt) {
		map.setMapCursor('default');
	});

	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	gridLayer = new FeatureLayer(url + "/17", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		visible : true,
		id : "gridLayer"
	});
	map.addLayer(gridLayer);
	
	gridLayer.on("mouse-over", function(evt) {
		map.setMapCursor('pointer');
	});
	gridLayer.on("mouse-out", function(evt) {
		map.setMapCursor('default');
	});

	/*gridLayer.setMaxScale(0);
	gridLayer.setMinScale(4508.935440959931);*/
	
	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	shopLayer = new FeatureLayer(url + "/18", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		maxScale : 0,
		minScale : 4508.935440959931,
		visible : true,
		id : "shopLayer"
	});
	map.addLayer(shopLayer);

	shopLayer.setMaxScale(0);
	shopLayer.setMinScale(4508.935440959931);
	
	shopLayer.on("mouse-over", function(evt) {
		map.setMapCursor('pointer');
	});
	shopLayer.on("mouse-out", function(evt) {
		map.setMapCursor('default');
	});
	
	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	userLayer = new FeatureLayer(url + "/19", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		maxScale : 0,
		minScale : 4508.935440959931,
		visible : true,
		id : "userLayer"
	});
	map.addLayer(userLayer);

	userLayer.setMaxScale(0);
	userLayer.setMinScale(4508.935440959931);
	
	userLayer.on("mouse-over", function(evt) {
		map.setMapCursor('pointer');
	});
	userLayer.on("mouse-out", function(evt) {
		map.setMapCursor('default');
	});
	

	gsvc = new GeometryService(arcGisUrl
			+ "/arcgis/rest/services/Utilities/Geometry/GeometryServer");

	toolbar = new Draw(map);
	dojo.connect(toolbar, "onDrawEnd", addToMap);
	dojo.connect(partLayer, "onClick", showPartDetail);
	dojo.connect(gridLayer, "onClick", showgridDetail);
	dojo.connect(shopLayer, "onClick", showShopDetail);
	dojo.connect(userLayer, "onClick", showUserDetail);
});

//网格展示信息
function showgridDetail(evt){
	console.log("gridLayer:click");
	if (evt.graphic) {
		console.log("grid:click");
		var id = evt.graphic.attributes.id;
		var url = window.rootPath+"/ui/index/getGridView/"+id;
		$('#gridIframe').attr('src',url);
		$('#gridModal').modal('show');
	}
};
//网格部门对应人员信息
function showdeptUserDetail(deptId){
		var url = window.rootPath+"/ui/index/getDeptFollowView/"+deptId;
		$('#deptIframe').attr('src',url);
		$('#deptModal').modal('show');
	
};
//部件展示信息
function showPartDetail(evt){
	console.log("partLayer:click");
	if (evt.graphic) {
		console.log("part:click");
		var id = evt.graphic.attributes.id;
		if(evt.graphic.attributes.isGrid==1){
			var url = window.rootPath+"/ui/index/getGridView/"+id;
			$('#gridIframe').attr('src',url);
			$('#gridModal').modal('show');
		}else{
			var url = window.rootPath+"/ui/index/getPartView/"+id;
			$('#partIframe').attr('src',url);
			$('#partModal').modal('show');
		}
	}
};

//商铺展示信息
function showShopDetail(evt){
	console.log("shopLayer:click");
	if (evt.graphic) {
		console.log("shop:click");
		var id = evt.graphic.attributes.id;
		var url = window.rootPath+"/ui/index/getShopView/"+id;
		$('#shopIframe').attr('src',url);
		$('#shopModal').modal('show');
	}
};
//人员展示信息
function showUserDetail(evt){
	console.log("userLayer:click")
	if (evt.graphic) {
		console.log("user:click");
		var id = evt.graphic.user.id;
		var isfollow=evt.graphic.isfollow;
		var url = window.rootPath+"/ui/index/getUserView/"+id+"/"+isfollow;
		$('#userIframe').attr('src',url);
		$('#userModal').modal('show');
	}
}

function openModal(type){
	if(type="event"){
		var url = window.rootPath+"/ui/index/getEventFollowView";
		$('#eventIframe').attr('src',url);
		$('#eventModal').modal('show');
	}
}
function addToMap(geometry) {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.

	$('body').css('cursor', 'default');
	map.setMapCursor('default');

	map.showZoomSlider(); // 在地图上显示的缩放滑块
	// 判断几何图形的类型
	switch (geometry.type) {
	case "point":
		var symbolurl = getIconForSelectNode();
		var symbol = new esri.symbol.PictureMarkerSymbol({
			"url" : symbolurl, // 图标路径
			"width" : 20, // 图标的宽度
			"height" : 20
		// 图标的高度
		});
		break;
	case "polyline":
		var symbol = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([ 255,
						0, 0 ]), 4);
		break;
	case "polygon":

		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 145, 0, 0.35 ]));
		/*
		 * // 测量面积 require( [ "esri/tasks/AreasAndLengthsParameters" ],
		 * function(AreasAndLengthsParameters) { var areasAndLengthParams = new
		 * AreasAndLengthsParameters(); areasAndLengthParams.lengthUnit =
		 * esri.tasks.GeometryService.UNIT_KILOMETER;
		 * areasAndLengthParams.areaUnit =
		 * esri.tasks.GeometryService.UNIT_SQUARE_KILOMETERS; gsvc.simplify([
		 * geometry ], function(simplifiedGeometries) {
		 * areasAndLengthParams.polygons = simplifiedGeometries;
		 * gsvc.areasAndLengths(areasAndLengthParams); }); });
		 */
		break;
	case "extent":
		/*var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;*/
		var graphics = partLayer.graphics;
		var results = [];
		var ids = "";
		for (var i = 0; i < graphics.length; i++) {
			if (geometry.contains(graphics[i].geometry) && graphics[i].attributes&&graphics[i].attributes.part
					&&graphics[i].attributes.part.partType&&graphics[i].attributes.part.partType.value=="1") {// &&graphics[i].pointType==tvPointType
				results.push(graphics[i].attributes);
				ids += graphics[i].attributes.id + ",";
			}
		}
		console.log("TV list:"+ids);
		jQuery('#videoModal').modal('show');
		//初始化参数
		currentResults=results;
		tvRow=1;
		tvColumn=1;
		TVwidthscale =12;
		TVheight =600;
		currentPageNum=1;
		$("#pageNum").html(currentPageNum);
		
		CreateTV(currentResults,currentPageNum);
		//$("#videoModal").modal("show");
		return;
	case "multipoint":
		var symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND, 20,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 0, 0, 0 ]), 1), new dojo.Color([ 255,
						255, 0, 0.5 ]));
		break;
	}
	var graphic = new esri.Graphic(geometry, symbol);

	map.graphics.add(graphic);
	var data = {};

	if (geometry.type == "polyline" && geometry.paths != undefined) {
		data.longitude = geometry.paths[0][0][0];
		data.latitude = geometry.paths[0][0][1];
		map.graphics.add(createPoint(data, "../img/location_start.png",25,25));

		data.longitude = geometry.paths[0][geometry.paths[0].length - 1][0];
		data.latitude = geometry.paths[0][geometry.paths[0].length - 1][1];
		map.graphics.add(createPoint(data, "../img/location_end.png",25,25));

		var textSymbol = new esri.symbol.TextSymbol("测量长度:");

		var point = {
			"geometry" : {
				"type" : "point",
				"x" : data.longitude,
				"y" : data.latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			}
		};

		text_graphic = new esri.Graphic(point);
		text_graphic.setSymbol(textSymbol);
		map.graphics.add(text_graphic);
	}
	if (geometry.type == "polygon" && geometry.rings != undefined) {
		for (var i = 0; i < geometry.rings[0].length; i++) {
			data.longitude = geometry.rings[0][i][0];
			data.latitude = geometry.rings[0][i][1];
			map.graphics.add(createPoint(data, "../img/location_start.png",25,25));
		}
		var textSymbol = new esri.symbol.TextSymbol("测量面积:");
		var point = graphic.geometry.getCentroid();
		text_graphic = new esri.Graphic(point, textSymbol);
		map.graphics.add(text_graphic);

	}
	// map.graphics.add(graphic); // 将绘图加入到图层中

	// 进行投影转换，完成后调用projectComplete

	MeasureGeometry(geometry);

};
//默认线样式
function getLineDefaultSymbol(){
	var symbol = new esri.symbol.SimpleLineSymbol(
			esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([ 255,
			                                                           145, 0 ]), 4);
	return symbol;
}
function getLineHighSymbol(){
	var symbol = new esri.symbol.SimpleLineSymbol(
			esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([ 255,
					0, 0 ]), 4);
	return symbol;
}
//默认网格样式
function getPolygonDefaultSymbol() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 145, 0,
					0.35 ]));

	return symbol;
}
//高亮网格样式
function getPolygonHighSymbol() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 255, 0,
					0.75 ]));
	return symbol;
}
function clearuserLayer(){
	closeSocketList();
	userLayer.clear();
	if(intervalflashTime){
		clearInterval(intervalflashTime);
		intervalflashTime=null;
	}
	if(intervalflashTimeEvent){
		clearInterval(intervalflashTimeEvent);
		intervalflashTimeEvent=null;
	}
	if(intervalflashTimePart){
		clearInterval(intervalflashTimePart);
		intervalflashTimePart=null;
	}

	if(intervalflashTimeWarning){
		clearInterval(intervalflashTimeWarning);
		intervalflashTimeWarning=null;
	}
	
	$('#registerEventName').val('');
	$('#registerEventAccTime').val('');
	$('#gridName').val('');
	$('#eventName').val('');
	$('#registerEventSeriousLevelTitle').val('');
	$('#registerEventContent').val('');
	$('#registerEventMemo').val('');
	
	$('#eventInfoDiv').hide();
}
function setUserFollow(userid,isfollow){
	$('#userModal').modal('hide');
	for(var i=0;i<userLayer.graphics.length;i++){
		if(userLayer.graphics[i].user && userLayer.graphics[i].user.id==userid){
			if(userLayer.graphics[i].geometry.type=="polyline"){
				if(isfollow=="0"){
					userLayer.graphics[i].hide();
				}else if(isfollow=="1"){
					userLayer.graphics[i].show();
				}		
		}
		userLayer.graphics[i].isfollow=isfollow;
		}
	}
};
function getUserToMapIds(list){
	$('#deptModal').modal('hide');
	var ids="";
	for(var i=0;i<list.length;i++){
		ids+=list[i]+",";
	}
	ids=ids.substring(0,ids.length-1);
	var url=window.rootPath+"/ui/index/getUserListByIds/"+ids;
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "get",
		dataType:"json",
		success:function(data){
			var users = data.users;
			partLayer.clear();
			gridLayer.clear();
			highLayer.clear();
			shopLayer.clear();
			clearuserLayer();
			$("#search").val('');
			initFollowPerson(users);
			initfollowState();
			for(var i=0;i<list.length;i++){
				MessageSocketForFollow(list[i]);
			}
		}
	});
};

function getEventToMap(data){
	$('#eventModal').modal('hide');
	
	partLayer.clear();
	gridLayer.clear();
	highLayer.clear();
	shopLayer.clear();
	clearuserLayer();
	
	if(data){
		$('#registerEventName').val(data.registerEventName);
		$('#registerEventAccTime').val(moment(data.registerEventAccTime).format('YYYY/MM/DD HH:mm'));
		$('#gridName').val(data.gridName);
		$('#eventName').val(data.eventName);
		$('#registerEventSeriousLevelTitle').val(data.registerEventSeriousLevelTitle);
		$('#registerEventContent').val(data.registerEventContent);
		$('#registerEventMemo').val(data.registerEventMemo);
		
		$('#eventInfoDiv').show();
		
		var temp = createEventPoint(data);
		userLayer.add(temp);
		var temp_point_fick = createFlickerEventPoint(data);
		userLayer.add(temp_point_fick);
		map.centerAndZoom(temp.geometry, map.getLevel());
		// 防异步错误
		if(intervalflashTimeEvent){
			clearInterval(intervalflashTimeEvent);
			intervalflashTimeEvent=null;
		}
		// 单位数据刷新
		intervalflashTimeEvent = setInterval(function() {
			refreashFlickerEventPoint();
		}, 75);
	}
	
	var url=window.rootPath+"/ui/index/getEventUserListById/"+data.eventTaskUser;
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "get",
		dataType:"json",
		success:function(data){
			var users = data.users;
			$("#search").val('');
			initFollowPerson(users);
			initfollowState();
		}
	});
};


function createFlickerEventPoint(data) {		
	var	symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 0, 255 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 0, 255, 1 ]) // 颜色和透明度
		);
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
		var graphic = new esri.Graphic(myPoint);
		 graphic.symbol = symbol;
		 graphic.attributes = data;
//		 graphic.user = data;
		 graphic.pointType = showFlickerEventPointType;
	return graphic;
};
function refreashFlickerEventPoint() {
	var len =userLayer.graphics.length;
	var graphics = userLayer.graphics;
	for (var i = 0; i < len; i++) {
		var graphic = graphics[i];
		if (graphic.pointType == showFlickerEventPointType ) {
			var symbol = graphic.symbol;
			if (symbol) {
				symbol.color.a -= 0.05;
				symbol.setSize(symbol.size + 8);
	
				if (symbol.color.a <= 0) {
					symbol.color.a = 1;
					symbol.setSize(1);
				}
				graphic.setSymbol(symbol);
			}
		}
	}
};


function createEventPoint(data){
	var longitude =  data.longitude;
	var latitude = data.latitude;
	if(longitude == 0 || latitude == 0){
		return null;
	}
	
	var icon = data.registerEventType.iconAddress;
	if (icon && icon!='') {
		icon = window.rootPath + '/'+icon;
	}else{
		icon = defaultEventTypeIcon;
	}
	icon = defaultEventTypeIcon;
	var symbol = new esri.symbol.PictureMarkerSymbol(icon, 40, 40).setOffset(0,20);
	var myPoint = {
			"geometry" : {
				"type" : "point",
				"x" : longitude,
				"y" : latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"attributes" : data,
			"symbol" : symbol
	};
	
	var graphic = new esri.Graphic(myPoint);
	graphic.symbol = symbol;
	graphic.attributes = data;
	
	return graphic;
}
// 创建图形
function createArea(data,num) {
	if (data.details) {
		var rings = [];

		var points = [];

		for (var i = 0; i < data.details.length; i++) {
			points.push([]);
		}

		for (var i = 0; i < data.details.length; i++) {
			var point = [];
			point.push(data.details[i].longtitude);
			point.push(data.details[i].latitude);

			points[data.details[i].longlatOrder] = point;
		}
		rings.push(points);

		var symbol = getPolygonDefaultSymbol();

		if(num==1){
			symbol=getPolygonHighSymbol();
		}
		
		var myPolygon = {
			"geometry" : {
				"rings" : rings,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"symbol" : {
				"color" : [ 0, 0, 0, 64 ],
				"outline" : {
					"outline" : [ 0, 0, 0, 255 ],
					"width" : 1,
					"type" : "esriSLS",
					"style" : "esriSFSSolid"
				}
			}
		};

		var graphic = new esri.Graphic(myPolygon);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.gridDetails = data.details;
		//gridLayer.add(graphic);
		return graphic;
	}
};
//创建图形
function createLine(data,num,isfollow) {
	if (data) {
		var paths = [];

		var points = [];

		for (var i = 0; i < data.length; i++) {
			points.push([]);
		}

		for (var i = 0; i < data.length; i++) {
			var point = [];
			point.push(data[i].longitude);
			point.push(data[i].latitude);
			points[i] = point;
		}
		paths.push(points);

		var symbol = getLineDefaultSymbol();

		if(num==1){
			symbol=getLineHighSymbol();
		}
		
		var myLine = {
			"geometry" : {
				"paths" : paths,
				"type": "polyline",
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"symbol" :symbol
		};

		var graphic = new esri.Graphic(myLine);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.user=data[0].user;
		graphic.isfollow=isfollow;
		return graphic;
	}
};
function createPoint(data, symbolurl,width,height) {
	var symbol = new esri.symbol.PictureMarkerSymbol({
		"url" : symbolurl, // 图标路径
		"width" : width, // 图标的宽度
		"height" : height
	// 图标的高度
	});

	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	/*
	 * , "infoTemplate": { "title": "sssss", "content": "latude:${Field}" }
	 */
	};
	var geometry = {
		"type" : "point",
		"x" : data.longitude,
		"y" : data.latitude,
		"spatialReference" : {
			"wkid" : 4326
		}
	};

	var graphic = new esri.Graphic(myPoint);
	graphic.symbol = symbol;
	graphic.attributes = data;
	// map.graphics.add(graphic);
	return graphic;
}
// 投影转换完成后调用方法
function MeasureGeometry(geometry) {
	require(
			[ "esri/tasks/AreasAndLengthsParameters",
					"esri/tasks/LengthsParameters" ],
			function(AreasAndLengthsParameters, LengthsParameters) {
				// 如果为线类型就进行lengths距离测算
				if (geometry.type == "polyline") {
					var lengthParams = new esri.tasks.LengthsParameters();
					lengthParams.polylines = [ geometry ];
					lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
					lengthParams.geodesic = true;
					lengthParams.polylines[0].spatialReference = new esri.SpatialReference(
							4326);
					gsvc.lengths(lengthParams);
					dojo.connect(gsvc, "onLengthsComplete", outputDistance);
				}
				// 如果为面类型需要先进行simplify操作在进行面积测算
				else if (geometry.type == "polygon") {
					var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
					areasAndLengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
					areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_SQUARE_METERS;
					this.outSR = new esri.SpatialReference({
						wkid : 102113
					});
					gsvc
							.project(
									[ geometry ],
									this.outSR,
									function(geometry) {
										gsvc
												.simplify(
														geometry,
														function(
																simplifiedGeometries) {
															areasAndLengthParams.polygons = simplifiedGeometries;
															areasAndLengthParams.polygons[0].spatialReference = new esri.SpatialReference(
																	102113);
															gsvc
																	.areasAndLengths(areasAndLengthParams);
														});
									});
					dojo.connect(gsvc, "onAreasAndLengthsComplete",
							outputAreaAndLength);
				}
			});
};
// 显示测量面积
function outputAreaAndLength(result) {
	// alert(result.areas[0].toFixed(3)+ "平方米");
	var textSymbol = new esri.symbol.TextSymbol("测量面积:"
			+ result.areas[0].toFixed(3) + "平方米");
	/*
	 * var textSymbol = { type: "text", // autocasts as new TextSymbol() color:
	 * "white", haloColor: "black", haloSize: "1px", text: "You are here",
	 * xoffset: 3, yoffset: 3, font: { // autocast as new Font() size: 20,
	 * family: "sans-serif", weight: "bolder" } };
	 */
	textSymbol.setFont({ // autocast as new Font()
		size : 20,
		family : "sans-serif",
		weight : "bolder"
	});
	textSymbol.setColor("white");
	text_graphic.setSymbol(textSymbol);

	console.log(result.areas[0].toFixed(3) + "平方米");
};
// 显示测量距离
function outputDistance(result) {
	var textSymbol = new esri.symbol.TextSymbol("测量长度:"+result.lengths[0].toFixed(3) + "米");
	textSymbol.setFont({ // autocast as new Font()
		size : 20,
		family : "sans-serif",
		weight : "bolder"
	});
	textSymbol.setColor("red");
	text_graphic.setSymbol(textSymbol);
	//alert(result.lengths[0].toFixed(3) + "米");
	console.log(result.lengths[0].toFixed(3) + "米");
}

	jQuery(document).ready(function () {
		$(window).resize(function(){
			var rightHeight=$("#left").height()-$("#footer").height()-$("#header").height();
			
			$("#map").height(rightHeight);
			$("#map").css({"height":+$("#right").height()+"px"}); 
		});
		getInfo();
		setInterval(realValueShow,10000);
	});
	
	function realValueShow() {
		var url=window.rootPath+"/ui/index/getAlarmData";
        jQuery.ajax({
            url:encodeURI(url),
            cache:false,
            type : "get",
            dataType:"json",
            success:function(data){
           	 	jQuery('#realreportNum').html(data.realreportNum);
           	 	jQuery('#finishreportNum').html(data.finishreportNum);
           	 	jQuery('#dealreportNum').html(data.dealreportNum);
           	 	jQuery('#undealreportNum').html(data.undealreportNum);
            }
        })
		
		var realpartNum = Math.round(Math.random() * 1000 + 2000);
		var normalpartNum = Math.round(Math.random() * 1000 + 1000);
		var alarmpartNum = Math.round(Math.random() * 500 + 500);
		var breakdownpartNum = Math.round(Math.random() * 500);
		
		jQuery('#realpartNum').html(realpartNum);
	 	jQuery('#normalpartNum').html(normalpartNum);
	 	jQuery('#alarmpartNum').html(alarmpartNum);
	 	jQuery('#breakdownpartNum').html(breakdownpartNum);
		
	}
	
	function getInfo(){
		 var url=window.rootPath+"/ui/index/getConfigData";
         jQuery.ajax({
             url:encodeURI(url),
             cache:false,
             type : "get",
             dataType:"json",
             success:function(data){         
            	 jQuery('#realreportNum').html(data.statis.realreportNum);
            	 	jQuery('#finishreportNum').html(data.statis.finishreportNum);
            	 	jQuery('#dealreportNum').html(data.statis.dealreportNum);
            	 	jQuery('#undealreportNum').html(data.statis.undealreportNum);
            	 	
            	 	jQuery('#realpartNum').html(0);
            	 	jQuery('#normalpartNum').html(0);
            	 	jQuery('#alarmpartNum').html(0);
            	 	jQuery('#breakdownpartNum').html(0);
            	 	
            	 	//部件信息
            	 	var parts = data.parts;
            	 	var partHtml = '';
            	 	for(var i=0;i<parts.length;i++){
            	 		if(parts[i].isParent > 0){
            	 			partHtml += '<dt class="list_dt partdt" dataId="'+parts[i].id+'"><span class="_after"></span><p>'+ parts[i].partName +'</p><i class="list_dt_icon"></i></dt>';
                	 		partHtml	 += '<dd class="list_dd" id="dd'+parts[i].id+'"></dd>';
            	 		}else{
            	 			partHtml += '<dt class="list_dt onePart" dataId="'+parts[i].id+'"><span class="_after"></span><p>'+ parts[i].partName +'</p><i class="list_dt_icon"></i></dt>';
                	 		partHtml	 += '<dd class="list_dd" id="dd'+parts[i].id+'"></dd>';
            	 		}
            	 	}
            	 	jQuery('#part').empty();
    				jQuery('#part').append(partHtml);
    				
    				//部门信息
    				var depts=data.depts;
    				var deptHtml='';
    				if(data.depts.length>0){
    					deptHtml += ' <li class="list_li oneDept one_li" dataId="all"><p>'+ "所有人员" +'</p></li>';
    				}
    				for(var i=0;i<depts.length;i++){
    					if(depts[i].isParent > 0){
    						deptHtml += '<dt class="list_dt deptdt" dataId="'+depts[i].id+'"><span class="_after"></span><p>'+ depts[i].groupName +'</p><i class="list_dt_icon"></i></dt>';
    						deptHtml	 += '<dd class="list_dd" id="dd'+depts[i].id+'"></dd>';
            	 		}else{
            	 			deptHtml += ' <li class="list_li oneDept one_li" dataId="'+depts[i].id+'"><p>'+ depts[i].groupName +'</p></li>';
            	 			//deptHtml += '<dt class="list_dt oneDept" dataId="'+depts[i].id+'"><span class="_after"></span><p>'+ depts[i].groupName +'</p><i class="list_dt_icon"></i></dt>';
            	 			//deptHtml	 += '<dd class="list_dd" id="dd'+depts[i].id+'"></dd>';
            	 		}
    				}
    				jQuery('#dept').empty();
    				jQuery('#dept').append(deptHtml);
    				//网格信息
    				var options = data.options;
    				var optionHtml = '';
            	 	for(var i=0;i<options.length;i++){
            	 		optionHtml += '<dt class="list_dt oneGrid" dataId="'+options[i].id+'"><span class="_after"></span><p>'+ options[i].title +'</p></dt>';
            	 		optionHtml	 += '<dd class="list_dd" id="op'+options[i].id+'"></dd>';
            	 	}
            	 	
            	 	//添加商铺信息
            	 	optionHtml += '<dt class="list_dt shopShow" dataId="ShopShow"><span class="_after"></span><p>商铺</p></dt>';
        	 		optionHtml	 += '<dd class="list_dd" id="opShopShow"></dd>';
            	 	
            	 	jQuery('#grid').empty();
    				jQuery('#grid').append(optionHtml);
    				
    				/*var grids = data.grids;
    				for(var i=0;i<grids.length;i++){
    					var gridHtml = '';
    					if($('#g'+grids[i].typeOpt.id).length > 0){
    						gridHtml = '<li class="list_li oneGrid one_li" dataId="'+grids[i].id+'"><p>'+ grids[i].gridName +'</p></li>';
        					jQuery('#g'+grids[i].typeOpt.id).append(gridHtml);
    					}else{
    						gridHtml = '<ul id="g'+grids[i].typeOpt.id+'"><li class="list_li oneGrid one_li" dataId="'+grids[i].id+'"><p>'+ grids[i].gridName +'</p></li></ul>';
        					jQuery('#op'+grids[i].typeOpt.id).append(gridHtml);
    					}
    					
    				}*/
             }
         })
	}
	
	$("body").on("click",'.partdt',function () {
		var clickObj =  $(this);
		var id = clickObj.attr('dataId');
		var url=window.rootPath+"/ui/index/getPartNext/"+id;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var parts = data.parts;
        	 		var partHtml = '<ul>';
	        	 	for(var i=0;i<parts.length;i++){
	        	 		if(parts[i].isParent > 0){
	        	 			partHtml += ' <li class="list_li" dataId="'+parts[i].id+'">';
	        	 			partHtml += '<dt class="list_dt partdt" dataId="'+parts[i].id+'"><span class="_after"></span><p>'+ parts[i].partName +'</p><i class="list_dt_icon"></i></dt>';
                	 		partHtml	 += ' <dd class="list_dd" id="dd'+parts[i].id+'"></dd>';
                	 		partHtml	 += '</li>';
	        	 			
	        	 		}else{
	        	 			partHtml += ' <li class="list_li onePart one_li" dataId="'+parts[i].id+'"><p>'+ parts[i].partName +'</p></li>';
	        	 		}
	        	 	}
	        	 	partHtml += '</ul>';
        	 		jQuery('#dd'+id).empty();
        	 		jQuery('#dd'+id).append(partHtml);
        	 		setSiblings(clickObj);
			}
		});
		
	})
	$("body").on("click",'.deptdt',function () {
		var clickObj =  $(this);
		var id = clickObj.attr('dataId');
		var url=window.rootPath+"/ui/index/getDeptNext/"+id;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var depts = data.depts;
        	 		var deptHtml = '<ul>';
	        	 	for(var i=0;i<depts.length;i++){
	        	 		if(depts[i].isParent > 0){
	        	 			deptHtml += ' <li class="list_li" dataId="'+depts[i].id+'">';
	        	 			deptHtml += '<dt class="list_dt deptdt" dataId="'+depts[i].id+'"><span class="_after"></span><p>'+ depts[i].groupName +'</p><i class="list_dt_icon"></i></dt>';
	        	 			deptHtml	 += ' <dd class="list_dd" id="dd'+depts[i].id+'"></dd>';
	        	 			deptHtml	 += '</li>';
	        	 			
	        	 		}else{
	        	 			deptHtml += ' <li class="list_li oneDept one_li" dataId="'+depts[i].id+'"><p>'+ depts[i].groupName +'</p></li>';
	        	 			//deptHtml += ' <li class="list_li" dataId="'+depts[i].id+'">';
	        	 			//deptHtml += '<dt class="list_dt oneDept" dataId="'+depts[i].id+'"><span class="_after"></span><p>'+ depts[i].groupName +'</p><i class="list_dt_icon"></i></dt>';
            	 			//deptHtml	 += '<dd class="list_dd" id="dd'+depts[i].id+'"></dd>';
            	 			//deptHtml	 += '</li>';
	        	 		}
	        	 	}
	        	 	deptHtml += '</ul>';
        	 		jQuery('#dd'+id).empty();
        	 		jQuery('#dd'+id).append(deptHtml);
        	 		setSiblings(clickObj);
			}
		});
		
	})
	
	
	function getPartToMap(id){
		var url=window.rootPath+"/ui/index/getPartList/"+id;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var parts = data.parts;
				partLayer.clear();
				gridLayer.clear();
				highLayer.clear();
				shopLayer.clear();
				clearuserLayer();
				$("#search").val('');
				
				for(var i=0;i<parts.length;i++){
					var partBaseInfo = parts[i];
					var part = partBaseInfo.part;
					var icon = part.iconAddress;
					
					if (icon && icon!='') {
						icon = window.rootPath + '/'+icon;
					}else{
						if(partBaseInfo.part&&partBaseInfo.part.partType&&partBaseInfo.part.partType.value=="1"){
							icon = window.rootPath + '/img/defaultTV.png';
						}else{
							icon = window.rootPath + '/img/defaultPart.png';
						}
						
					}
					var temp = createPoint(partBaseInfo, icon,20,20);
					partLayer.add(temp);
					/*if(i==0){
						map.centerAndZoom(temp.geometry, map.getLevel());
					}*/
				}
				//部件刷新检查
				// 防异步错误
				if(intervalflashTimePart){
					clearInterval(intervalflashTimePart);
					intervalflashTimeEvent=null;
				}
				// 单位数据刷新
				intervalflashTimePart = setInterval(function() {
					refreashPartStatus(id);
				}, 5000);

				// 防异步错误
				if(intervalflashTimeWarning){
					clearInterval(intervalflashTimeWarning);
					intervalflashTimeEvent=null;
				}
				// 单位数据刷新
				intervalflashTimeWarning = setInterval(function() {
					refreashFlickerWarningPoint();
				}, 75);
				
			}
		});
	}
	
	function refreashPartStatus(id){
		var url=window.rootPath+"/ui/index/refreashPartStatus/"+id;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var warnings = data.warnings;
				cleanWarningPoint();
				if(warnings){
					for(var i=0;i<warnings.length;i++){
						var temp = createFlickerWarningPoint(warnings[i]);
						partLayer.add(temp);
					}
				}
			}
		});
	}
	
	function createFlickerWarningPoint(data) {		
		var	symbol = new esri.symbol.SimpleMarkerSymbol(
					esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
					1, // 像素
					new esri.symbol.SimpleLineSymbol(
							esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
							new dojo.Color([ 255, 0, 0 ]), 0.1), // 颜色 1 // 像素 ),
					new dojo.Color([ 255, 0, 0, 1 ]) // 颜色和透明度
			);
		var myPoint = {
			"geometry" : {
				"type" : "point",
				"x" : data.longitude,
				"y" : data.latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"attributes" : data,
			"symbol" : symbol
		};
			var graphic = new esri.Graphic(myPoint);
			 graphic.symbol = symbol;
			 graphic.attributes = data;
			 graphic.pointType = showFlickerWaringPointType;
		return graphic;
	};
	function cleanWarningPoint(){
		var len =partLayer.graphics.length;
		var graphics = partLayer.graphics;
		for (var i = len - 1; i >= 0; i--) {
			var graphic = graphics[i];
			if (graphic.pointType == showFlickerWaringPointType ) {
				partLayer.remove(graphics[i]);
			}
		}
	}
	function refreashFlickerWarningPoint() {
		var len =partLayer.graphics.length;
		var graphics = partLayer.graphics;
		for (var i = 0; i < len; i++) {
			var graphic = graphics[i];
			if (graphic.pointType == showFlickerWaringPointType ) {
				var symbol = graphic.symbol;
				if (symbol) {
					symbol.color.a -= 0.05;
					symbol.setSize(symbol.size + 8);
		
					if (symbol.color.a <= 0) {
						symbol.color.a = 1;
						symbol.setSize(1);
					}
					graphic.setSymbol(symbol);
				}
			}
		}
	};
	
	$("body").on("click",'.griddt',function () {
		var clickObj =  $(this);
		setSiblings(clickObj);
	})

	$("body").on("click",'.onePart',function () {
		$('.listdt').slideUp();
		var id = $(this).attr('dataId');
		getPartToMap(id);
//		var id = "5bdfc0dd-8625-4f36-9ea3-1d89d9efcac4";
//		var url = window.rootPath+"/ui/index/getPartView/"+id;
//		$('#partIframe').attr('src',url);
//		$('#partModal').modal('show');
	});
	function getUserToMap(id){
		var url=window.rootPath+"/ui/index/getUserList/"+id;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var users = data.users;
				partLayer.clear();
				gridLayer.clear();
				highLayer.clear();
				shopLayer.clear();
				clearuserLayer();
				$("#search").val('');
				initFollowPerson(users);
				initfollowState();
			}
		});
	};
	function initfollowState(){
		for(var i=0;i<userLayer.graphics.length;i++){
				if(userLayer.graphics[i].geometry.type=="polyline"){
					if(userLayer.graphics[i].isfollow=="0"){
						userLayer.graphics[i].hide();
					}		
			}
		}	
	};
	function initFollowPerson(users){
		if(!users){
			return;
		}
		var isfollow="1";
		var list=[];
	    var currentUser='';
	    var icon = window.rootPath + '/img/defaultTipstaff.png';
		for(var i=0;i<users.length;i++){
			if(currentUser!=users[i].user.id&&list.length>0){
				var temp=createLine(list,0,isfollow);
				userLayer.add(temp);
				var temp_point_fick=createFlickerPoint({
					"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
				    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
				});
				temp_point_fick.user=temp.user;
				temp_point_fick.isfollow=isfollow;
				userLayer.add(temp_point_fick);
				var temp_point = createPoint({
					"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
				    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
				}, icon,20,20);
				temp_point.user =temp.user;
				temp_point.isfollow=isfollow;
				userLayer.add(temp_point);
				var line_des=addLineDes(users[i-1]);
				line_des.user =temp.user;
				line_des.isfollow=isfollow;
				userLayer.add(line_des);
				MessageSocketForFollow(temp.user.id);
				list=[];												
			}
			currentUser=users[i].user.id;
			list.push(users[i]);					
		}
		if(list.length>0){
			var temp=createLine(list,0,isfollow);
			userLayer.add(temp);
			var temp_point_fick = createFlickerPoint({
				"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
			    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
			});
			temp_point_fick.user=temp.user;
			temp_point_fick.isfollow=isfollow;
			userLayer.add(temp_point_fick);
			var temp_point = createPoint({
				"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
			    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
			}, icon,20,20);
			temp_point.user =temp.user;
			temp_point.isfollow =isfollow;
			userLayer.add(temp_point);
			var line_des=addLineDes(users[users.length-1]);
			line_des.user=temp.user;
			line_des.isfollow=isfollow;
			userLayer.add(line_des);
			MessageSocketForFollow(temp.user.id);
			list=[];
			map.centerAndZoom(temp.geometry.paths[0][temp.geometry.paths[0].length-1], map.getLevel());
			// 防异步错误
			if(intervalflashTime){
				clearInterval(intervalflashTime);
				intervalflashTime=null;
			}
			// 单位数据刷新
			intervalflashTime = setInterval(function() {
				refreashFlickerPoint();
			}, 75);
		}
	};
	function createFlickerPoint(data) {		
		var	symbol = new esri.symbol.SimpleMarkerSymbol(
					esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
					1, // 像素
					new esri.symbol.SimpleLineSymbol(
							esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
							new dojo.Color([ 255, 0, 0 ]), 0.1), // 颜色 1 // 像素 ),
					new dojo.Color([ 0, 255, 0, 1 ]) // 颜色和透明度
			);
		var myPoint = {
			"geometry" : {
				"type" : "point",
				"x" : data.longitude,
				"y" : data.latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"attributes" : data,
			"symbol" : symbol
		};
			var graphic = new esri.Graphic(myPoint);
			 graphic.symbol = symbol;
			 graphic.attributes = data;
			 graphic.user = data;
			 graphic.pointType = showFlickerPointTyp
		return graphic;
	};
	function refreashFlickerPoint() {
		var len =userLayer.graphics.length;
		var graphics = userLayer.graphics;
		for (var i = 0; i < len; i++) {
			var graphic = graphics[i];
			if (graphic.pointType == showFlickerPointTyp ) {
				var symbol = graphic.symbol;
				if (symbol) {
					symbol.color.a -= 0.05;
					symbol.setSize(symbol.size + 8);

					if (symbol.color.a <= 0) {
						symbol.color.a = 1;
						symbol.setSize(1);
					}
					graphic.setSymbol(symbol);
				}
			}
		}
	};
	function addLineDes(data){
		var textSymbol = new esri.symbol.TextSymbol("人员:"+data.user.name);
		var point = {
			"geometry" : {
				"type" : "point",
				"x" : data.longitude,
				"y" : data.latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			}
		};
		var text_graphic = new esri.Graphic(point);
		text_graphic.setSymbol(textSymbol);
		text_graphic.attributes=data;
		return text_graphic;
	};
	function realValueLine() {
		var lastPoint=[];
		for(var i=0;i<userLayer.graphics.length;i++){
			var geometry =userLayer.graphics[i].geometry;
			if(userLayer.graphics[i].geometry.type=="polyline"){
					lastPoint=[geometry.paths[0][geometry.paths[0].length-1][0]+0.00001,
				               geometry.paths[0][geometry.paths[0].length-1][1]+0.00001];
					geometry.paths[0].push(lastPoint)				
			}else{
				geometry.x=lastPoint[0];
				geometry.y=lastPoint[1];
			}
			userLayer.graphics[i].setGeometry(geometry);
		}
	};
	function realValueLineForSocket(map) {
		var isOk=1;
		for(var i=0;i<userLayer.graphics.length;i++){
			var geometry =userLayer.graphics[i].geometry;
			if(userLayer.graphics[i].user.id==map.user.user.id){
				var lastPoint=[map.user.longitude,
			               map.user.latitude];
				if(userLayer.graphics[i].geometry.type=="polyline"){
					geometry.paths[0].push(lastPoint)				
			}else{
				geometry.x=lastPoint[0];
				geometry.y=lastPoint[1];
			}
			userLayer.graphics[i].setGeometry(geometry);
			isOk=0;
			}
		}
		if(isOk==1){
			var users=[];
			users.push(map.user);
			initFollowPerson(users);
			initfollowState();
		}
	};
	$("body").on("click",'.oneDept',function () {
		$('.listdt').slideUp();
		var id = $(this).attr('dataId');
		showdeptUserDetail(id);
		//getUserToMap(id);
	});
	
	function getGridToMap(id){
		var url=window.rootPath+"/ui/index/getgridList/"+id;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var grids = data.grids;
				gridLayer.clear();
				partLayer.clear();
				highLayer.clear();
				shopLayer.clear();
				clearuserLayer();
				$("#search").val('');
				for(var i=0;i<grids.length;i++){
					var gridBaseInfo = grids[i];
					if(gridBaseInfo.details!=null&&gridBaseInfo.details.length>1)
						{
						var temp =createArea(gridBaseInfo,0);
						gridLayer.add(temp);
						}
					else if(gridBaseInfo.details!=null&&gridBaseInfo.details.length==1){
						gridBaseInfo.longitude=gridBaseInfo.details[0].longtitude;
					    gridBaseInfo.latitude=gridBaseInfo.details[0].latitude;
					    gridBaseInfo.isGrid=1;
						var icon = part.iconAddress;
						if (icon && icon!='') {
							icon = window.rootPath + '/'+icon;
						}else{
							icon = window.rootPath + '/img/defaultPoint.png';
						}
						var temp = createPoint(gridBaseInfo, icon,20,20);
						partLayer.add(temp);
					}
					/*if (i == 0) {
						map.centerAndZoom(temp.geometry.getCentroid(), map
								.getLevel());
					}*/
				}
				map.centerAndZoom({'x':gridCenterX,'y':gridCenterY}, map.getLevel());
			}
		});
	}

	function getShowToMap(){
		var url=window.rootPath+"/ui/index/getShowList/";
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var shops = data.shops;
				gridLayer.clear();
				partLayer.clear();
				highLayer.clear();
				shopLayer.clear();
				clearuserLayer();
				$("#search").val('');
				for(var i=0;i<shops.length;i++){
					var shop = shops[i];
					var temp =createShopPoint(shop);
					if(temp != null){
						shopLayer.add(temp);
						//map.centerAndZoom(temp.geometry, map.getLevel());
					}
					
				}
				map.centerAndZoom({'x':gridCenterX,'y':gridCenterY}, map.getLevel());
			}
		});
	}
	
	function createShopPoint(data){
		var longitude =  data.longitude;
		var latitude = data.latitude;
		if(longitude == 0 || latitude == 0){
			return null;
		}
		var symbol = new esri.symbol.PictureMarkerSymbol(defaultShopIcon, 40, 40).setOffset(0,20);
		var myPoint = {
				"geometry" : {
					"type" : "point",
					"x" : longitude,
					"y" : latitude,
					"spatialReference" : {
						"wkid" : 4326
					}
				},
				"attributes" : data,
				"symbol" : symbol
		};
		
		var graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.attributes = data;
		
		return graphic;
	}
	
	$("body").on("click",'.oneGrid',function () {
		$('.listdt').slideUp();
		var id = $(this).attr('dataId');
		getGridToMap(id);
	});

	$("body").on("click",'.shopShow',function () {
		$('.listdt').slideUp();
		getShowToMap();
	});
	
	function setSiblings(obj) {
		$('.list_dd').stop();
		obj.siblings("dt").removeAttr("id");
		if(obj.attr("id")=="open"){
			obj.removeAttr("id").siblings("dd").slideUp();
		}else{
			obj.attr("id","open").next().slideDown().siblings("dd").slideUp();
		}
	};
	$("body").on("click",'#drawpolyline',function () {
		map.graphics.clear();
		toolbar.deactivate(); // 关闭工具栏并激活地图导航.
		toolbar.activate(drawHandler.POLYLINE);
		$('body').css('cursor', 'crosshair');
		map.setMapCursor('crosshair');
		$('.listdt').slideUp();
	});
	$("body").on("click",'#exchangeTwoD',function () {
		$('.listdt').slideUp();
		if($("#twoDState").html()=="2.5D隐藏"){
			dynamic.hide();
			$("#twoDState").html("2.5D显示");
		}else{
			dynamic.show();
			$("#twoDState").html("2.5D隐藏");
		}
	});
	$("body").on("click",'#selectTV',function () {
		$('.listdt').slideUp();
		toolbar.deactivate(); // 关闭工具栏并激活地图导航.
		toolbar.activate(drawHandler.EXTENT);
		$('body').css('cursor', 'crosshair');
		map.setMapCursor('crosshair');
	});
	$("body").on("click",'#drawpolygon',function () {
		map.graphics.clear();
		toolbar.deactivate(); // 关闭工具栏并激活地图导航.
		toolbar.activate(drawHandler.POLYGON);
		$('body').css('cursor', 'crosshair');
		map.setMapCursor('crosshair');
		$('.listdt').slideUp();
	});
	$("body").on("click",'#canceldraw',function () {
		toolbar.deactivate(); // 关闭工具栏并激活地图导航.
		$('body').css('cursor', 'default');
		map.setMapCursor('default');
		$('.listdt').slideUp();
	});
	$("body").on("click",'#cleardraw',function () {
		map.graphics.clear();
		toolbar.deactivate(); // 关闭工具栏并激活地图导航.
		$('body').css('cursor', 'default');
		map.setMapCursor('default');
		$('.listdt').slideUp();
	});
	function getVideoToMap(){
		var url=window.rootPath+"/ui/index/getVideoPartList";
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var parts = data.videos;
				partLayer.clear();
				gridLayer.clear();
				highLayer.clear();
				shopLayer.clear();
				clearuserLayer();
				$("#search").val('');
				for(var i=0;i<parts.length;i++){
					var partBaseInfo = parts[i];
					var part = partBaseInfo.part;
					var icon = part.iconAddress;
					if (icon && icon!='') {
						icon = window.rootPath + '/'+icon;
					}else{
						icon = window.rootPath + '/img/defaultTV.png';
					}
					var temp = createPoint(partBaseInfo, icon,20,20);
					partLayer.add(temp);
					/*if(i==0){
						map.centerAndZoom(temp.geometry, map.getLevel());
					}*/
				}
			}
		});
	}
	$("body").on("click",'#videototal',function () {
		$('.listdt').slideUp();
		getVideoToMap();
	});
	function getcurrentGraphicsByValue(txt) {
		highLayer.clear();
		if(txt==undefined||txt==""){
			return;
		}
		//部件检索
		var graphics = partLayer.graphics;
		for (var i = 0; i < graphics.length; i++) {
			if (graphics[i] && graphics[i].geometry.type == "point") {
				if(graphics[i].attributes&&graphics[i].attributes.isGrid==1){
					if (graphics[i].attributes.gridIdentify
							&& graphics[i].attributes.gridIdentify.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.gridName
							&& graphics[i].attributes.gridName.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.gridState
							&& graphics[i].attributes.gridState.title.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.gridMemo
							&& graphics[i].attributes.gridMemo.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					}
				}
				else if (graphics[i].attributes) {
					if (graphics[i].attributes.partName
							&& graphics[i].attributes.partName.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.partIdentify
							&& graphics[i].attributes.partIdentify.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.manufacturer
							&& graphics[i].attributes.manufacturer.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.deviceIdentify
							&& graphics[i].attributes.deviceIdentify
									.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					} else if (graphics[i].attributes.hierarchy
							&& graphics[i].attributes.hierarchy.groupName
									.indexOf(txt) != -1) {
						highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
						continue;
					}
				}
			}
		}
		//网格检索
		var graphics = gridLayer.graphics;
		for (var i = 0; i < graphics.length; i++) {
			if (graphics[i] && graphics[i].geometry.type == "polygon") {
				if (graphics[i].attributes) {
					if (graphics[i].attributes.gridIdentify
							&& graphics[i].attributes.gridIdentify.indexOf(txt) != -1) {
						highLayer.add(createArea(graphics[i].attributes,1));
						continue;
					} else if (graphics[i].attributes.gridName
							&& graphics[i].attributes.gridName.indexOf(txt) != -1) {
						highLayer.add(createArea(graphics[i].attributes,1));
						continue;
					} else if (graphics[i].attributes.gridState
							&& graphics[i].attributes.gridState.title.indexOf(txt) != -1) {
						highLayer.add(createArea(graphics[i].attributes,1));
						continue;
					} else if (graphics[i].attributes.gridMemo
							&& graphics[i].attributes.gridMemo.indexOf(txt) != -1) {
						highLayer.add(createArea(graphics[i].attributes,1));
						continue;
					}
				}
			}
		}
	};
	$("body").on("click",'.searchBtn',function () {
		getcurrentGraphicsByValue($("#search").val());
	});
	$("body").on("click",'.resetBtn',function () {
		$("#search").val('');
		highLayer.clear();
	});
	
	
	$('#partModal').on('hidden.bs.modal', function () {
		$('#partIframe').attr('src','');
	});
	//人员跟踪定位socket
	function MessageSocketForFollow(userid){
		if(!socketList){
			socketList=[];
		}else{
			for(var i=0;i<socketList.length;i++){
				if(socketList[i].userid==userid){
					return;
				}
			}
		}
		var socket;  
	    if(typeof(WebSocket) == "undefined") {  
	        console.log("您的浏览器不支持WebSocket");  
	    }else{  
	        console.log("您的浏览器支持WebSocket");
	    }
	    socket = new WebSocket("ws"+window.location.origin.substring(4)+"/wcsi/wcsi-websocket/"+$("#accountId").val()+"/followPersonLocation"+userid);  
	    //打开事件  
	    socket.onopen = function() {  
	        console.log("Socket 已打开");  
	        //socket.send("这是来自客户端的消息" + location.href + new Date());  
	    }; 
	    var socketInfo={
	    		"userid":userid,
	    		"socket":socket
	    };
	    
	    socketList.push(socketInfo);
	    //获得消息事件  
	    socket.onmessage = function(msg) {  
	        console.log(msg.data);
	        var message =JSON.parse(msg.data);
	        if(message.followMap!=undefined){
	        	realValueLineForSocket(message.followMap);
	        }
	    };  
	    /*//关闭事件  
	    socket.onclose = function() {  
	        console.log("Socket已关闭");  
	    };  */
	    //发生了错误事件  
	    socket.onerror = function() {  
	    	console.log("Socket发生了错误");  
	    }
	};
	function closeSocketList(){
		if(socketList){
        	for(var i=0;i<socketList.length;i++){
        		socketList[i].socket.close();
        	}
        	socketList=null;
        } 
	};
	
	$(window).unload(function(){  
		clearuserLayer();
      });
	$("#nextPage").on("click",function(){
		if(!(currentResults.length>currentPageNum*tvRow*tvColumn)){
			alert("已经是最后一页");
		}else{
			currentPageNum++;
			CreateTV(currentResults,currentPageNum);
		}
	});
	$("#previousPage").on("click",function(){
		if(currentPageNum==1){
			alert("已经是第一页");
		}else{
			currentPageNum--;
			CreateTV(currentResults,currentPageNum);
		}
	});
	var tvRow=1;
	var tvColumn=1;
	var TVwidthscale =12;
	var TVheight =600;
	var currentPageNum=1;
	var currentResults=[];
	function CreateTV(results,pageNum)
	{
		if(results.length>1){
			TVheight=285;
			tvColumn=2;
			tvRow=2;
			TVwidthscale=6;
		}else{
			TVheight=570;
			tvColumn=1;
			tvRow=1;
			TVwidthscale=12;
		}
		var isIECore='';
		if(!!window.ActiveXObject || "ActiveXObject" in window)
		    isIECore=true;
		else  
		    isIECore=false;
		
		var object_str="";
		
		if(results.length<=((pageNum-1)*tvColumn*tvRow)){
			return;
		}
		$("#pageNum").html(currentPageNum);
		$("#TVdiv").empty();
		for(var i=((pageNum-1)*tvColumn*tvRow);i<results.length;i++){
			if((i-((pageNum-1)*tvColumn*tvRow))>=4){
				break;
			}
			if (isIECore) {	
				object_str+='<div class="col-md-'+TVwidthscale+'" style="padding-left: 0px;padding-right: 0px;">'
					+'<div class="box box-info" style="margin-bottom: 0px;border-top-width: 0px;" id="'+i+'_td" useradress="'+results[i].interfaceAddress+'" userchannel="'+results[i].interfacePort+'">'
					+'<object id="'+i+'_csocx" classid="clsid:59EA8A50-4FC1-406a-A471-595247AB2E41" codebase="/wcsi/tvfile/CISDITV.cab" width="100%" height="'+TVheight+'px"></object></div></div>';
			}
			else {
				object_str+='<div class="col-md-'+TVwidthscale+'" style="padding-left: 0px;padding-right: 0px;">'
					+'<div class="box box-info" style="margin-bottom: 0px;border-top-width: 0px;" id="'+i+'_td" useradress="'+results[i].interfaceAddress+'" userchannel="'+results[i].interfacePort+'">'
					+'<object id="'+i+'_csocx" clsid="{59EA8A50-4FC1-406a-A471-595247AB2E41}" type="application/x-itst-activex"  progid="/wcsi/tvfile/CISDITV.cab" width="100%" height="'+TVheight+'px"></object></div></div>';
			}
		}
		$('#TVdiv').append(object_str);
		
		for(var i=((pageNum-1)*tvColumn*tvRow);i<results.length;i++){
			if((i-((pageNum-1)*tvColumn*tvRow))>=4){
				break;
			}
			WatchTV(i+"_csocx",i+"_td");
		}
	};
	function WatchTV(id,tdid)
	{
		var ocxKq = document.getElementById(id);
		var ocxKqj =$("#"+tdid);
		var ip =ocxKqj.attr("useradress");
		var channel=ocxKqj.attr("userchannel");
		setTimeout(function(){
			ocxKq.InstallView(ip,channel);
			ocxKq.OpenStream();
		},500);
	};